import { check } from 'meteor/check';
import { ChannelMembers, isMember } from '/imports/models/ChannelMembers';
import { Notifications } from '/imports/models/Notifications';

Meteor.methods({
  quitChannel(options) {
    check(options.id, String);

    return ChannelMembers.remove({
      user_id: Meteor.userId(),
      channel_id: options.id
    });
  },

  removeMember(options) {
    check(options.id, String);

    return ChannelMembers.remove({
      _id: options.id
    });
  },

  inviteMember(options) {
    check(options.id, String);
    check(options.channelId, String);
    check(options.friendId, String);

    return Notifications.insert({
      type: 'invite.user.join.channel',
      user_id: options.friendId, // 通知接收者
      details: {
        _id: options.id,
        channelId: options.channelId,
        user_id: Meteor.userId(),
        username: Meteor.user().username,
        avatar: Meteor.user().profile.avatar,
        text: '邀请你加入频道'
        // 用户[username]邀请你加入频道[频道ID]
      }
    });
  },

  addMember(options) {
    check(options.id, String);
    check(options.channelId, String);

    Notifications.remove({
      _id: options.id
    });

    if (!isMember(options.id, Meteor.userId())) {
      return ChannelMembers.insert({
        user_id: Meteor.userId(),
        channel_id: options.channelId
      });
    }
    
    return true;
  }
});